<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" placeholder="用户名"><span></span>
    <br/>
    <input type="password" placeholder="密码"><span></span>
    <br/>
    <input type="button" value="登录" onclick="loginClick()">
    <script src="../js/axios.min.js"></script>
    <script src="../js/api.js"></script>
    <script>
        let ipts = document.querySelectorAll("input");
        let span = document.querySelector("span");
        let isUsername = false;
        let isPassword = false;
        ipts[0].onblur = function(){
            let str = this.value;
            let reg = /^[a-z]\w{5,17}$/i;
            if(reg.test(str)){
                span.innerHTML = "格式正确"
                span.style.color = "green"
                isUsername = true;
                axios.get(checkusernameAPI,{
                    params:{username: str}
                }).then(res=>{
                    let {data} = res;
                    console.log(data);
                   
                })

            }else{
                span.innerHTML = "只能输入字母、数字、下划线"
                span.style.color = "red"
                isUsername = false;
            }
        }
        ipts[1].onblur = function(){
            let str = this.value;
            let reg = /^\S{6,16}$/;
            if(reg.test(str)){
                this.nextElementSibling.innerHTML = "";
                isPassword = true;
            }else{
                this.nextElementSibling.innerHTML = "格式有误，必须是6-16个字符，区分大小写";
                this.nextElementSibling.style.color = "gray";
                isPassword = false;
            }
        }

        async function loginClick(){
            let username = ipts[0].value;
            let password = ipts[1].value;
            if(isUsername && isPassword){
                let {data} = await axios.get(loginAPI, {
                    params:{username, password}
                })
                console.log(data);
                // console.log(data.data.id);
                // console.log(data.data.username);
                // console.log(data.data.token);
                localStorage.setItem("uid", data.data.id);
                localStorage.setItem("token", data.data.token);
                localStorage.setItem("username", data.data.username);
                alert(data.msg);
                if(data.code == 1){
                    location.href = "index.html"
                }
            }
        }
    </script>
</body>
</html>